<template>

  <v-container fluid class="custom-container noPdlr pdt-60 custom-bg overhidden" v-touch="{
      left: () => tabsSwitch('left'),
      right: () => tabsSwitch('right'),

    }" align="center" justify="center">

    <xy-header-top title='预警中心'>
      <v-btn icon slot="left" small @click="routerHome">
        <v-icon class="white--text">iconfont-icon iconleft</v-icon>
      </v-btn>
    </xy-header-top>

    <!-- <xy-alert :dialog="dialog" v-on:isShowDialogFrom="isShowDialog"></xy-alert> -->
    <!-- 从子组件发射过来的事件 -->
    <!-- <xy-store-tree :dialog="dialog" v-on:isShowDialogStore="isShowDialog"></xy-store-tree> -->
    <!-- <v-subheader>当前{{userContext.role==='STORE'?'门店':'品牌'}}：{{userContext.nickname}}</v-subheader> -->
    <!-- <xy-Forewarning-choose-store v-if="role"></xy-Forewarning-choose-store> -->

    <v-tabs grow ref="tab">
      <v-tabs-slider style="color:#ff9859;"></v-tabs-slider>
      <v-tab @click="getList($event)" ref="tabOne">今日到期 {{expirationData.expireTodayTotal}}</v-tab>
      <v-tab @click="getList($event)" ref="tabSec">即将到期 {{expirationData.expireSoonTotal}}</v-tab>
      <v-tab @click="getList($event)" ref="tabThird">已到期 {{expirationData.expiredTotal}}</v-tab>
    </v-tabs>


    <div ref="scrollWrapper" class="scrollWrapper">

      <v-layout wrap style="padding:10px;">

        <h4 v-if="isRefreshing" class="text-center pa-3 subtitle-2 isRefreshing">正在刷新...</h4>

        <v-flex xs6 sm6 md6 pa-1 v-for="(item,index) in foreWarningMaterialCard" :key="index">
          <!--
            :checkStatus="checkStatus[index]"
            只有danger可以点击
            @click.native="item.warningType=='danger' && checkHandler(index,item.materialName)"
          -->
          <xy-forewarning-material-card :card-text="item.materialName" :warning-type="item.warningType"
                                        :expire-time="item.expireTime" :quantity="item.quantity">
          </xy-forewarning-material-card>
        </v-flex>

        <h4 v-if="noMoreData" class="text-center pa-3 subtitle-2 noMoreData">没有更多数据了</h4>
        <div class="text-center mx-auto" style="width:100%" v-if="isShowUpLoadingShow">
          <v-progress-circular indeterminate color="#999"></v-progress-circular>
          <span class="subtitle-2 pl-2" style="color: #999">加载中...</span>
        </div>

      </v-layout>

    </div>

    <!--
      props传给子组件的值
      dialog                  是否显示对话
      expirationMaterialName  将过期的物料名传给子组件
      efcTurnOffDialog        接收从子组件发射回来的事件
      currrntTabIndex         目前点击索引传给遮罩层对话框
    -->

    <!-- <xy-dialog :dialog="dialog" :expirationMaterialName="expirationMaterialName" :currrntTabIndex="currrntTabIndex"
      v-on:efcTurnOffDialog="isShowDialog" v-on:efcDeleteMaterial="deleteMaterial">
    </xy-dialog> -->

  </v-container>

</template>


<script>
    import xyForewarningCategoryCard from '../../views/card/ForewarningCategoryCard';
    import xyForewarningMaterialCard from '../../views/card/ForewarningMaterialCard';
    import BScroll from 'better-scroll';
    import {mapState} from 'vuex';

    export default {
        components: {
            xyForewarningCategoryCard,
            xyForewarningMaterialCard,
            // xyStoreTree,
            // xyDialog
        },
        mounted() {
            //挂载后，将vuetify里的v-tab组件的z-index设置成3，用css设置无效
            this.$refs.tab.$el.children[0].style.zIndex = 3;
            //顶部tab数据
            this.$ajax.get("/inventory_warning/warning_total", {}).then(response => {
                this.expirationData = response.data;
            }).catch(error => {
                this.$message.error(error);
            });
            //预警物料列表
            this.loadData();

            if (!this.itemScroll) {

                this.itemScroll = new BScroll(this.$refs.scrollWrapper, {
                    startY: 0,
                    startX: 0,
                    scrollY: true,
                    scrollX: false,
                    scrollbar: false,
                    click: true,
                    tap: true,
                    pullUpLoad: true,
                    pullDownRefresh: true,
                });
                this.itemScroll.on('pullingDown', () => {
                    this.reloadData();
                    this.itemScroll.finishPullUp();
                    this.itemScroll.refresh();
                });

                this.itemScroll.on('pullingUp', () => {
                    this.upLoadData();
                });
            } else {
                this.itemScroll.refresh() // 让滚动条刷新一下: 重新统计内容的高度
            }
        },
        computed: {
            ...mapState([
                'userContext'
            ])
        },
        data() {
            return {
                isActive: false,
                //顶部tab过期物料总览
                expirationData: {},
                itemScroll: null,
                //没有更多的数据
                noMoreData: false,
                //是否正在刷新
                isRefreshing: false,
                dialog: false,
                //过期的物料名
                expirationMaterialName: "",
                //展示用
                foreWarningMaterialCard: [],
                foreWarningMaterialCardAry: [{
                    expireAry: [],
                }, {
                    expireAry: [],
                }, {
                    expireAry: [],
                }],
                //所处在哪个tab
                currrntTabIndex: 0,
                requiredPageNo: [{
                    page: 1
                }, {
                    page: 1
                }, {
                    page: 1
                }],
                requiredWarningType: "expire_today",
                isShowUpLoadingShow: false,
                loadDataIsEnd: false,
                limit: 10
            }
        },
        updated() {
            //当数据加载完毕以后通知better-scroll
            this.itemScroll.finishPullUp();
            //重新计算高度
            this.itemScroll.refresh();
        },
        methods: {
            //手势切换tab
            tabsSwitch(direction) {
                if (this.currrntTabIndex === 0) {
                    switch (direction) {
                        // case 'left':
                        //     this.$router.push('/tastyIndex');
                        //     break;
                        case 'right':
                            this.$refs.tabSec.$el.click();
                            break;
                    }
                } else if (this.currrntTabIndex === 1) {
                    switch (direction) {
                        case 'left':
                            this.$refs.tabOne.$el.click();
                            break;
                        case 'right':
                            this.$refs.tabThird.$el.click();
                            break;
                    }
                } else {
                    switch (direction) {
                        case 'left':
                            this.$refs.tabSec.$el.click();
                            break;
                        case 'right':
                            return;
                    }
                }
            },
            routerHome() {
                this.$router.push('/tastyIndex');
            },
            reloadData() {
                this.requiredPageNo[this.currrntTabIndex].page=1;
                // this.pageNo = 1;
                this.isShowUpLoadingShow = false;
                this.isRefreshing = true;
                this.noMoreData = false;
                this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry = [];
                this.loadData();
            },
            loadData() {
                this.$ajax.get("/inventory_warning/paging", {
                    params: {
                        storeId: this.userContext.store.id,
                        warningType: this.requiredWarningType,
                        pageNo: this.requiredPageNo[this.currrntTabIndex].page,
                        limit: this.limit,
                        // brandId: "",
                        // searchKey: "",
                    }
                }).then(response => {
                    if (response.code === "ok") {
                        this.isShowUpLoadingShow = false;
                        this.isRefreshing = false;
                        //如果返回的数据为空或者数据的条数小于默认的限制条数，说明没有更多数据了
                        this.loadDataIsEnd = !response.data || response.data.length < this.limit;
                        this.noMoreData = this.loadDataIsEnd;
                        for (let i = 0; i < response.data.length; i++) {
                            //生成卡片的参数
                            let obj = {
                                materialName: "",
                                quantity: 0,
                                expireTime: 0,
                                warningType: ""
                            };
                            if (this.currrntTabIndex === 0) {
                                obj.warningType = "safe";
                            } else if (this.currrntTabIndex === 1) {
                                obj.warningType = "warn";
                            } else {
                                obj.warningType = "danger";
                            }
                            obj.materialName = response.data[i].material.name;
                            obj.quantity = response.data[i].auditQuantity;
                            obj.expireTime = response.data[i].expireTime;

                            this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry.push(obj);
                        }
                        this.foreWarningMaterialCard = this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry;
                    }
                }).then(() => {
                    this.itemScroll.finishPullUp();
                    this.itemScroll.finishPullDown();
                    this.itemScroll.refresh();
                })
            },
            upLoadData() {

                this.noMoreData = false;
                this.isShowUpLoadingShow = true;
                let expireAry = ['expireTodayTotal', 'expireSoonTotal', 'expiredTotal'];
                //二维数组，当前索引下的数组小于，顶部对应tab卡上的数值
                if (this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry.length < this.expirationData[expireAry[this
                    .currrntTabIndex]]) {
                    this.requiredPageNo[this.currrntTabIndex].page++;
                    this.loadData();
                } else {
                    this.isShowUpLoadingShow = false;
                    this.noMoreData = true;
                }
            },
            //点击tab获取数据
            getList(e, index) {
                this.isActive = index;
                //切换后要将滚动条重置到顶部，否则在某个tab下只要发生过滚动，切换到另一个tab的时候首次加载会重复请求
                if (this.itemScroll.y !== 0) {
                    this.itemScroll.scrollTo(0, 0);
                }
                let ary = e.target.innerText.split(" ");

                if (ary[0] === "今日到期") {
                    this.requiredWarningType = "expire_today";
                    this.currrntTabIndex = 0;
                } else if (ary[0] === "即将到期") {
                    this.requiredWarningType = "expire_soon";
                    this.currrntTabIndex = 1;
                } else {
                    this.requiredWarningType = "expired";
                    this.currrntTabIndex = 2;
                }

                //防止点击tab切换重复请求,只有当当前索引下的数组长度为0的情况下，切换tab才会去请求
                if (this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry.length === 0) {
                    this.noMoreData = false;
                    this.loadData();
                } else {
                    let expireAry = ['expireTodayTotal', 'expireSoonTotal', 'expiredTotal'];
                    this.noMoreData = this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry.length >= this.expirationData[expireAry[
                        this.currrntTabIndex]];
                    this.foreWarningMaterialCard = this.foreWarningMaterialCardAry[this.currrntTabIndex].expireAry;
                }
            },

            isShowDialog(val) {
                //从子组件中传过来的值
                this.dialog = val
            },

            checkHandler(index, title) {
                //点击卡片将所点击的card的索引赋值给currentIndex
                // this.currrntTabIndex = index;
                this.dialog = true;
                this.expirationMaterialName = title;
                //把对应的状态存进数组里
                // this.$set(this.checkStatus, index, !this.checkStatus[index]);
            },

            deleteMaterial(val) {
                this.dialog = false;
            }

        }
    }

</script>

<style scoped>
  .v-application--is-ltr .v-tabs-bar.v-tabs-bar--is-mobile:not(.v-tabs-bar--show-arrows) > .v-slide-group__wrapper > .v-tabs-bar__content > .v-tab:first-child,
  .v-application--is-ltr .v-tabs-bar.v-tabs-bar--is-mobile:not(.v-tabs-bar--show-arrows) > .v-slide-group__wrapper > .v-tabs-bar__content > .v-tabs-slider-wrapper + .v-tab {
    margin-left: 0 !important;

  }

  .v-tab.v-tab--active {
    color: #ff9859 !important;
    caret-color: #ff9859 !important;
  }

  .col {
    padding: 5px;
  }

  .v-tab {
    padding: 0
  }

  .v-speed-dial {
    position: absolute;
  }

  .v-btn--floating {
    position: relative;
  }

  .v-btn--fab.v-size--default.v-btn--absolute.v-btn--bottom {
    bottom: 28px;
  }

  .v-btn--fab.v-size--default.v-btn--absolute.v-btn--top {
    top: 50px;
  }

  .v-content {
    background: #fff;
  }

  .noPdlr {
    padding-left: 0;
    padding-right: 0;
  }

  .dp-flex {
    display: flex;
    z-index: 100;
    width: 100%;
    justify-content: space-between;
  }

  .dp-flex div {
    text-align: center;
    width: 100%;
    z-index: 100;
    background: #fff;
    height: 48px;
    line-height: 48px;
    color: rgba(0, 0, 0, 0.54);
    font-size: 0.875rem;

  }


  .actived-tab {
    color: #ff9859 !important;
    border-bottom: 2px solid #ff9859;
    background-color: rgb(255, 242, 234) !important;
    transition: all 0.3s linear;
  }

  .scrollWrapper{
      height: 390px;
  }

  .custom-bg{
      background-color: rgb(243, 247, 253) !important;
  }

  .overhidden{
      overflow: hidden;
  }

</style>
